import service from "@/service"
import Magic from "@/utils/Magic";
import useStorage from "@/utils/useStorage";
import type { InjectionKey } from "vue"
import { createStore, Store, useStore as baseUseStore } from 'vuex'

export type configStoreState = {
  base: Base.dto,
  config: Config.InstanceGroup;
  currentProjectName: keyof Config.InstanceGroup;
  currentBaseConfig: Config.Option;
  currentGroup: Config.Group[];
  currentItems: Config.Item[];
}

const storage = useStorage()

// 定义 injection key
export const configStoreKey: InjectionKey<Store<configStoreState>> = Symbol()

export const configStore = createStore<configStoreState>({
  state: {
    base: {
      defaultPendantMax: 3,
      defaultPendantReplay: 3,
    },
    config: {},
    currentProjectName: storage.get(Magic.currentProjectName) || '',
    currentBaseConfig: {} as Config.Option,
    currentGroup: [],
    currentItems: []
  },
  actions: {
    /** 切换项目 */
    toggleProject({state, commit}, payload: string) {
      state.currentProjectName = payload;
      storage.set(Magic.currentProjectName, payload, -1)
      commit('updateCurrentPorjectInfo')
    },
    async pull({state, commit}) {
      state.config = await service.getConfig()

      !state.currentProjectName && (state.currentProjectName = Object.keys(state.config)[0]);
      commit('updateCurrentPorjectInfo')
    },
    async save({state, dispatch}) {
      state.config[state.currentProjectName].config = state.currentBaseConfig
      state.config[state.currentProjectName].groups = state.currentGroup
      state.config[state.currentProjectName].items = state.currentItems

      await service.saveConfig(state.config)
      await dispatch('pull')
    },
    async pullBase({state}) { state.base = await service.getBase() },
    async saveBase({state}) { await service.saveBase(state.base) },
    async reset({dispatch}) {
      await service.resetConfig()
      await dispatch('pull')
    }
  },
  mutations: {
    updateCurrentPorjectInfo(state) {
      console.log(state.config[state.currentProjectName].config);
      state.currentBaseConfig = state.config[state.currentProjectName].config;
      state.currentGroup      = state.config[state.currentProjectName].groups.sort((a, b) => a.zIndex - b.zIndex);
      state.currentItems      = state.config[state.currentProjectName].items;
    },
    useItems(state, itemIds: Config.ItemId[]) {
      for (const itemId of itemIds) {
        const item = state.currentItems.find(k => k.id === itemId)
        item && item.currentCount ++
      }
    },
    removeItems(state, itemIds: Config.ItemId[]) {
      for (const itemId of itemIds) {
        const idx = state.currentItems.findIndex(k => k.id === itemId)
        idx !== -1 && state.currentItems.splice(idx, 1)
      }
    }
  }
})

configStore.dispatch('pull')
configStore.dispatch('pullBase')

export function useConfigStore () {
  return baseUseStore(configStoreKey)
}
